//
//  ConversationController.swift
//  FMRadio
//
//  Created by 范东 on 2022/7/27.
//

import UIKit
import FDUIKit

class ConversationController: BaseViewController {
    
    var titleView: TUINaviBarIndicatorView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let conv = TUIConversationListController()
        conv.delegate = self
        addChild(conv)
        view.addSubview(conv.view)
        conv.view.frame = CGRect(x: 0, y: 0, width: .screenW, height: .screenH - .tabBarHeight - .topHeight - 50)
        
        setupNavigation()
        NotificationCenter.default.addObserver(self, selector: #selector(onFriendInfoChanged(notice:)), name: NSNotification.Name(rawValue: "FriendInfoChangedNotification"), object: nil)
    }
    
    @objc func onFriendInfoChanged(notice: Notification){
        let friendInfo = notice.object as! V2TIMFriendInfo
        for vc in children {
            if vc.isKind(of: TUIConversationListController.classForCoder()) {
                let listVC = vc as! TUIConversationListController
                let dataProvider = listVC.dataProvider
                for cellData in dataProvider.dataList {
                    if cellData.userID == friendInfo.userID {
                        var title = friendInfo.friendRemark
                        if title?.count == 0 {
                            title = friendInfo.userFullInfo.nickName
                        }
                        if title?.count == 0 {
                            title = friendInfo.userID
                        }
                        cellData.title = title ?? ""
                        listVC.tableView.reloadData()
                        break
                    }
                }
                break
            }
        }
    }
    
    func setupNavigation(){
        titleView = TUINaviBarIndicatorView()
        titleView.setTitle("消息")
        navigationItem.titleView = titleView
        navigationItem.title = ""
        V2TIMManager.sharedInstance().add(self)
    }
    
    @objc func pushToChatViewController(_ groupID: String, userID: String){
        let topVC = navigationController?.topViewController!
        var isSameTarget = false
        var isInChat = false
        if topVC?.isKind(of: TUIC2CChatViewController.classForCoder()) ?? false || topVC?.isKind(of: TUIGroupChatViewController.classForCoder()) ?? false {
            let cellData = (topVC as! TUIBaseChatViewController).conversationData
            isSameTarget = cellData?.groupID == groupID || cellData?.userID == userID
            isInChat = true
        }
        if isInChat && isSameTarget {
            return
        }
        if isInChat && !isSameTarget {
            navigationController?.popViewController(animated: false)
        }
        let conversationData = TUIChatConversationModel()
        conversationData.userID = userID
        conversationData.groupID = groupID
        let chatVC = ConversationController.getChatViewController(model: conversationData)
        navigationController?.pushViewController(chatVC, animated: true)
    }

}

extension ConversationController: TUIConversationListControllerListener{
    func conversationListController(_ conversationController: UIViewController, didSelectConversation conversationCell: TUIConversationCell) {
        // 会话列表点击事件，通常是打开聊天界面
        let chatVc = ConversationController.getChatViewController(model: ConversationController.getConversationModel(data: conversationCell.convData))
        navigationController?.pushViewController(chatVc, animated: true)
        
    }
    
    class func getConversationModel(data: TUIConversationCellData) -> TUIChatConversationModel{
        let model = TUIChatConversationModel()
        model.conversationID = data.conversationID;
        model.userID = data.userID
        model.groupType = data.groupType
        model.groupID = data.groupID
        model.userID = data.userID
        model.title = data.title
        model.faceUrl = data.faceUrl
        model.avatarImage = data.avatarImage
        model.draftText = data.draftText
        model.atMsgSeqs = data.atMsgSeqs
        return model
    }
    
    class func getChatViewController(model: TUIChatConversationModel) -> TUIBaseChatViewController{
        var chat: TUIBaseChatViewController?
        if model.userID.count > 0 {
            chat = TUIC2CChatViewController()
        }else if model.groupID.count > 0 {
            chat = TUIGroupChatViewController()
        }
        chat?.conversationData = model
        return chat!
    }
}

extension ConversationController: V2TIMSDKListener{
    func onConnecting() {
        onNetworkChanged(status: .TNet_Status_Connecting)
    }
    
    func onConnectSuccess() {
        onNetworkChanged(status: .TNet_Status_Succ)
    }
    
    func onConnectFailed(_ code: Int32, err: String!) {
        onNetworkChanged(status: .TNet_Status_ConnFailed)
    }
    
    func onNetworkChanged(status: TUINetStatus){
        TUITool.dispatchMainAsync {
            switch status {
            case .TNet_Status_Succ:
                self.titleView.setTitle("消息")
                self.titleView.stopAnimating()
                break
            case .TNet_Status_Connecting:
                self.titleView.setTitle("连接中...")
                self.titleView.startAnimating()
                break
            case .TNet_Status_Disconnect:
                self.titleView.setTitle("消息(未连接)")
                self.titleView.stopAnimating()
                break
            case .TNet_Status_ConnFailed:
                self.titleView.setTitle("消息(未连接)")
                self.titleView.stopAnimating()
                break
            default:
                break
            }
        }
    }
}
